package cn.aws360.boot.base.starter.config;

import cn.aws360.boot.base.api.pojo.properties.CorsProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author junnan
 */
@Configuration
@RequiredArgsConstructor
public class CorsAutoConfiguration implements WebMvcConfigurer {

    private final CorsProperties corsProperties;

    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setMaxAge(corsProperties.getMaxAge());
        config.addAllowedMethod(corsProperties.getAllowedMethods());
        config.addAllowedHeader(corsProperties.getAllowedHeaders());
        config.setAllowCredentials(corsProperties.isAllowCredentials());
        config.addAllowedOriginPattern(corsProperties.getAllowedOriginPattern());
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

}